#include "listen.h"
#include "export.h"


char *_file_back;

void __export(const char *mesg)
{
	char *loc;
	elog_xml_scanf(mesg, "<mesg>.<location>.%s", &loc);
	int type;
	elog_xml_scanf(mesg, "<mesg>.<format>.%i", &type);
	if (type == ELOG_EXP_STYLE_USER) {
		char *user_type;
		elog_xml_scanf(mesg, "<mesg>.<user>.%s", &user_type);
		char *out = elog_exp_html(loc, type, user_type);
		if (out) {
			elog_tlk_reply(_file_back, out);
			free(out);
		}
		free(user_type);

	} else {
		char *out = elog_exp_html(loc, type);
		if (out) {
			elog_tlk_reply(_file_back, out);
			free(out);
		}
	}


	free(loc);
}


void __command(const char *mesg)
{
#ifndef NO_GUI

	char *txt;
	elog_xml_scanf(mesg, "<mesg>.<body>.%s", &txt);
	if (txt == NULL)
		return;


	elog_gui_al_lock();
	int offset = elog_gui_al_cursor(-1);
	elog_gui_io_addUndoActionPtr(ELOG_GUI_IO_ACTION_PASTE, txt,
				     offset);
	elog_gui_al_insertStr(offset, txt);

	elog_gui_al_unlock();
#endif

}

void __fetch(const char *file)
{
#ifndef NO_GUI

	elog_gui_al_lock();
	char *txt = (char *) elog_gui_al_getSelectedText();
	elog_gui_al_unlock();

	elog_tlk_reply(_file_back, txt);

	free(txt);

#endif
}

void elog_lsn_initialize(const char *file)
{
#ifndef WIN32
	int fd0;
	char *opcode = malloc((sizeof *opcode) * (ELOG_LSN_MSG_SIZE + 1));
	fd0 = mkfifo(file, S_IFIFO | 0600);

	char *file1;
	elog_sp_cat(&file1, file, "1", NULL);
	mkfifo(file1, S_IFIFO | 0600);
	_file_back = file1;

	if (fd0 > 0) {
		elog_err_print_console
		    ("Failed to create FIFO pipe, you might as well quit:\n");
		//return;
	}

	while (1) {
		fd0 = open(file, O_RDONLY);
		int readen = read(fd0, opcode, ELOG_LSN_MSG_SIZE - 1) - 1;
		opcode[readen] = '\0';


		close(fd0);
		elog_lsn_process(file, opcode);
		usleep(150000);

	}

	printf("You shouldn't be reading this till the program closes\n");
	free(opcode);
#endif
}
void elog_lsn_process(const char *file, const char *mesg)
{
	char *type;
	elog_xml_scanf(mesg, "<mesg>.<type>.%s", &type);
	if (type == NULL)
		return;
	if (strcmp(type, ELOG_LSN_TYPE_COMMAND) == 0)
		__command(mesg);
	else if (strcmp(type, ELOG_LSN_TYPE_FETCH) == 0)
		__fetch(file);
	else if (strcmp(type, ELOG_LSN_TYPE_EXPORT) == 0)
		__export(mesg);
	free(type);
}

char *elog_lsn_listen(const char *file)
{
	int fd;
	char *opcode = malloc((sizeof *opcode) * (ELOG_LSN_MSG_SIZE + 1));


	fd = open(file, O_RDONLY);
	int readen = read(fd, opcode, ELOG_LSN_MSG_SIZE);
	if (readen < 0)
		return ELOG_ERROR;
	if (readen < (ELOG_LSN_MSG_SIZE)) {
		free(opcode);
		return NULL;
	}
	opcode[readen] = '\0';

	close(fd);


	return opcode;
}
